<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="en">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">


























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.0.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32.ico?v=7.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16.ico?v=7.0.0">


  <link rel="mask-icon" href="/images/logo.svg?v=7.0.0" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="最近在手动实现一套 IM 系统，关于数据传输格式的选择，犹豫了下，对比了 JSON 和 XML，最后选择了 Protobuf，本文旨在通过简单的案例阐述清楚其间的一些坑。">
<meta name="keywords" content="Google,IM,JAVA,JSON,Protobuf,XML,数据传输">
<meta property="og:type" content="article">
<meta property="og:title" content="protobuf 使用指南">
<meta property="og:url" content="https://blog-test.jetchen.cn/protobuf/index.html">
<meta property="og:site_name" content="嘎里三分熟">
<meta property="og:description" content="最近在手动实现一套 IM 系统，关于数据传输格式的选择，犹豫了下，对比了 JSON 和 XML，最后选择了 Protobuf，本文旨在通过简单的案例阐述清楚其间的一些坑。">
<meta property="og:locale" content="en">
<meta property="og:image" content="http://blogsource.chenkaikai.com/uploads/2019/05/Protobuf01.png">
<meta property="og:image" content="http://blogsource.chenkaikai.com/uploads/2019/05/1557490393359.jpg">
<meta property="og:image" content="http://blogsource.chenkaikai.com/uploads/2019/05/Protobuf02.png">
<meta property="og:image" content="http://blogsource.chenkaikai.com/cli_500px.png">
<meta property="og:updated_time" content="2019-05-12T06:05:37.609Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="protobuf 使用指南">
<meta name="twitter:description" content="最近在手动实现一套 IM 系统，关于数据传输格式的选择，犹豫了下，对比了 JSON 和 XML，最后选择了 Protobuf，本文旨在通过简单的案例阐述清楚其间的一些坑。">
<meta name="twitter:image" content="http://blogsource.chenkaikai.com/uploads/2019/05/Protobuf01.png">






  <link rel="canonical" href="https://blog-test.jetchen.cn/protobuf/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>protobuf 使用指南 | 嘎里三分熟</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">嘎里三分熟</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="Toggle navigation bar">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>Home</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about-me/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>About</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>Archives</a>

  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://blog-test.jetchen.cn/protobuf/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Jet Chen">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="嘎里三分熟">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">protobuf 使用指南

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              

              
                
              

              <time title="Created: 2019-05-12 13:48:21" itemprop="dateCreated datePublished" datetime="2019-05-12T13:48:21+08:00">2019-05-12</time>
            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/常用工具/" itemprop="url" rel="index"><span itemprop="name">常用工具</span></a></span>

                
                
                  , 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/常用工具/技能/" itemprop="url" rel="index"><span itemprop="name">技能</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><center>最近在手动实现一套 IM 系统，关于数据传输格式的选择，犹豫了下，对比了 JSON 和 XML，最后选择了 Protobuf，本文旨在通过简单的案例阐述清楚其间的一些坑。</center><br><a id="more"></a></p>
<hr>
<p>搜索微信公众号【 <strong>Jet与编程</strong> 】体验更多有趣功能和文章哦。</p>
<hr>
<h2 id="一、简介"><a href="#一、简介" class="headerlink" title="一、简介"></a>一、简介</h2><p>最近在手撸 IM 系统，关于数据传输格式的选择，犹豫了下，对比了 JSON 和 XML，最后选择了 Protobuf 作为数据传输格式。</p>
<p>毕竟 Google 出品，必属精品😂，<a href="https://developers.google.com/protocol-buffers/docs/proto3" target="_blank" rel="noopener">[官网地址]</a>。<br>好了，舔狗环节结束，关于技术选择，都是需要根据实际的应用场景的，否则都是耍流氓，下文会进行简单的对比，先来看看官网的介绍：</p>
<blockquote>
<p>他是一种与语言无关、与平台无关，是一种可扩展的用于序列化和结构化数据的方法，常用于用于通信协议，数据存储等。<br>他是一种灵活，高效，自动化的机制，用于序列化结构化数据，对比于 XML，他更小（3~10倍），更快（20~100倍），更简单。</p>
</blockquote>
<p>当然，最简单粗暴的理解方式，就是结合 JSON 和 XML 来理解，你可以暂时将他们仨理解成同一种类型的事物，但是呢，Protobuf 对比于他们两个，拥有着体量更小，解析速度更快的优势，所以，在 IM 这种通信应用中，非常适合将 Protobuf 作为数据传输格式。</p>
<h2 id="二、关于-proto3"><a href="#二、关于-proto3" class="headerlink" title="二、关于 proto3"></a>二、关于 proto3</h2><p>Protobuf 有两个大版本，proto2 和 proto3，同比 python 的 2.x 和 3.x 版本，如果是新接触的话，同样建议直接入手 proto3 版本。所以下文的描述都是基于 proto3 的。</p>
<p>proto3 相对 proto2 而言，简言之就是支持更多的语言（Ruby、C#等）、删除了一些复杂的语法和特性、引入了更多的约定等。</p>
<blockquote>
<p>为什么要关注语言，因为它不像 JSON 一样开箱即用，它依赖工具包来进行编译成 java 文件或 go 文件等。</p>
</blockquote>
<p>正如硬币的两面性一样，凡事皆有双面性，Protobuf 数据的体量更小，所以自然失去了人类的直接可读性， JSON 数据结构是可以很直观地阅读的，但是 Protobuf 我们需要借助工具来进行更友好地使用，所以，我们需要自定义一个 schema 来定义数据结构的描述，即下面的 message。</p>
<ul>
<li>Message</li>
</ul>
<p>举个很简单的栗子，摘自官网：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">syntax = &quot;proto3&quot;; // proto3 必须加此注解</span><br><span class="line"></span><br><span class="line">message SearchRequest &#123;</span><br><span class="line">  string query = 1;</span><br><span class="line">  int32 page_number = 2;</span><br><span class="line">  int32 result_per_page = 3;</span><br><span class="line">  enum Corpus &#123;</span><br><span class="line">    UNIVERSAL = 0;</span><br><span class="line">    WEB = 1;</span><br><span class="line">    IMAGES = 2;</span><br><span class="line">    LOCAL = 3;</span><br><span class="line">    NEWS = 4;</span><br><span class="line">    PRODUCTS = 5;</span><br><span class="line">    VIDEO = 6;</span><br><span class="line">  &#125;</span><br><span class="line">  Corpus corpus = 4;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面便是定义好的一个 message，里面包含：</p>
<ol>
<li>String 类型的 query，编号是 1 <strong>（注：字段必须有编号且编号不允许重复）</strong></li>
<li>int 类型的 page_number，编号是 2</li>
<li>枚举类型的 corpus <strong>（注：枚举内部的编号也不允许重复，并且第一个编号必须为0）</strong></li>
</ol>
<h2 id="三、对比-JSON-和-XML"><a href="#三、对比-JSON-和-XML" class="headerlink" title="三、对比 JSON 和 XML"></a>三、对比 JSON 和 XML</h2><p><img src="http://blogsource.chenkaikai.com/uploads/2019/05/Protobuf01.png" alt="对比图"></p>
<h2 id="四、应用"><a href="#四、应用" class="headerlink" title="四、应用"></a>四、应用</h2><p>此处以 Windows 为例，其他的都差不多。</p>
<ol>
<li>windows 安装</li>
</ol>
<ul>
<li>protoc 下载：<a href="https://github.com/protocolbuffers/protobuf/releases/tag/v3.7.1" target="_blank" rel="noopener">[官方下载地址]</a>，然后将 bin 路径添加到 path 环境变量下去</li>
<li>查看是否安装成功：控制台输入 <code>protoc --version</code> ，控制台输出版本信息代表成功，如： <code>libprotoc 3.7.1</code></li>
</ul>
<ol start="2">
<li>ideal 安装插件</li>
</ol>
<ul>
<li>ideal 插件库搜索安装 <strong>Protobuf Support</strong> 即可</li>
<li>此插件可以不用安装，但是这有助于一些源码阅读的便利性和一些编码提示<blockquote>
<p>IDE 最大的作用不就是快速编码嘛<br><img src="http://blogsource.chenkaikai.com/uploads/2019/05/1557490393359.jpg" alt></p>
</blockquote>
</li>
</ul>
<ol start="3">
<li><p>编写 proto 文件<br>定义一个 JetProtos.proto 文件</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">syntax = &quot;proto3&quot;; // PB协议版本</span><br><span class="line"></span><br><span class="line">import &quot;google/protobuf/any.proto&quot;; // 引用外部的message，可以是本地的，也可以是此处比较特殊的 Any</span><br><span class="line"></span><br><span class="line">package jet.protobuf; // 包名，其他 proto 在引用此 proto 的时候，就可以使用 test.protobuf.PersonTest 来使用，</span><br><span class="line">// 注意：和下面的 java_package 是两种易混淆概念，同时定义的时候，java_package 具有较高的优先级</span><br><span class="line"></span><br><span class="line">option java_package = &quot;com.jet.protobuf&quot;; // 生成类的包名，注意：会在指定路径下按照该包名的定义来生成文件夹</span><br><span class="line">option java_outer_classname=&quot;PersonTestProtos&quot;; // 生成类的类名，注意：下划线的命名会在编译的时候被自动改为驼峰命名</span><br><span class="line"></span><br><span class="line">message PersonTest &#123;  </span><br><span class="line">    int32 id = 1; // int 类型  </span><br><span class="line">    string name = 2; // string 类型  </span><br><span class="line">    string email = 3;  </span><br><span class="line">    Sex sex = 4; // 枚举类型  </span><br><span class="line">    repeated PhoneNumber phone = 5; // 引用下面定义的 PhoneNumber 类型的 message  </span><br><span class="line">    map&lt;string, string&gt; tags = 6; // map 类型  </span><br><span class="line">    repeated google.protobuf.Any details = 7; // 使用 google 的 any 类型  </span><br><span class="line"></span><br><span class="line">    // 定义一个枚举  </span><br><span class="line">    enum Sex &#123;      </span><br><span class="line">        DEFAULT = 0;      </span><br><span class="line">        MALE = 1;      </span><br><span class="line">        Female = 2;  </span><br><span class="line">    &#125;  </span><br><span class="line">    </span><br><span class="line">    // 定义一个 message  </span><br><span class="line">    message PhoneNumber &#123;    </span><br><span class="line">        string number = 1;    </span><br><span class="line">        PhoneType type = 2;    </span><br><span class="line">        </span><br><span class="line">        enum PhoneType &#123;      </span><br><span class="line">            MOBILE = 0;      </span><br><span class="line">            HOME = 1;      </span><br><span class="line">            WORK = 2;    </span><br><span class="line">        &#125;  </span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>编译成 java 文件<br>进入 proto 文件所在路径，输入下面 protoc 命令（后面有三部分参数），然后将编译得出的 java 文件拷贝到项目中即可（此 java 文件可以理解成使用的数据对象）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">protoc -I=./ --java_out=./ ./JetProtos.proto</span><br><span class="line">或</span><br><span class="line">protoc -proto_path=./ --java_out=./ ./JetProtos.proto</span><br></pre></td></tr></table></figure>
</li>
</ol>
<blockquote>
<p>参数说明：</p>
<ol>
<li>-I 等价于 -proto_path：指定 .proto 文件所在的路径</li>
<li>–java_out：编译成 java 文件时，标明输出目标路径</li>
<li>./JetProtos.proto：指定需要编译的 .proto 文件</li>
</ol>
</blockquote>
<ol start="5">
<li>使用</li>
</ol>
<ul>
<li><p>maven 引入指定包</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- protobuf --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span>     </span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.google.protobuf<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span>     </span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>protobuf-java<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span>     </span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.7.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>使用<br>序列化和反序列化有多种方式，可以是 byte[]，也可以是 inputStream 等，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jet.mini.protobuf;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.google.protobuf.ByteString;</span><br><span class="line"><span class="keyword">import</span> com.google.protobuf.InvalidProtocolBufferException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.ByteArrayInputStream;</span><br><span class="line"><span class="keyword">import</span> java.io.ByteArrayOutputStream;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span>: ProtoTest</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>: ProtoBuf 测试</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span>: Jet.Chen</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2019/5/8 9:55</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span>: 1.0</span></span><br><span class="line"><span class="comment"> **/</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ProtoTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">/** Step1：生成 personTest 对象 */</span></span><br><span class="line">            <span class="comment">// personTest 构造器</span></span><br><span class="line">            PersonTestProtos.PersonTest.Builder personBuilder = PersonTestProtos.PersonTest.newBuilder();</span><br><span class="line">            <span class="comment">// personTest 赋值</span></span><br><span class="line">            personBuilder.setName(<span class="string">"Jet Chen"</span>);</span><br><span class="line">            personBuilder.setEmail(<span class="string">"ckk505214992@gmail.com"</span>);</span><br><span class="line">            personBuilder.setSex(PersonTestProtos.PersonTest.Sex.MALE);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 内部的 PhoneNumber 构造器</span></span><br><span class="line">            PersonTestProtos.PersonTest.PhoneNumber.Builder phoneNumberBuilder = PersonTestProtos.PersonTest.PhoneNumber.newBuilder();</span><br><span class="line">            <span class="comment">// PhoneNumber 赋值</span></span><br><span class="line">            phoneNumberBuilder.setType(PersonTestProtos.PersonTest.PhoneNumber.PhoneType.MOBILE);</span><br><span class="line">            phoneNumberBuilder.setNumber(<span class="string">"17717037257"</span>);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// personTest 设置 PhoneNumber</span></span><br><span class="line">            personBuilder.addPhone(phoneNumberBuilder);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 生成 personTest 对象</span></span><br><span class="line">            PersonTestProtos.PersonTest personTest = personBuilder.build();</span><br><span class="line"></span><br><span class="line">            <span class="comment">/** Step2：序列化和反序列化 */</span></span><br><span class="line">            <span class="comment">// 方式一 byte[]：</span></span><br><span class="line">            <span class="comment">// 序列化</span></span><br><span class="line"><span class="comment">//            byte[] bytes = personTest.toByteArray();</span></span><br><span class="line">            <span class="comment">// 反序列化</span></span><br><span class="line"><span class="comment">//            PersonTestProtos.PersonTest personTestResult = PersonTestProtos.PersonTest.parseFrom(bytes);</span></span><br><span class="line"><span class="comment">//            System.out.println(String.format("反序列化得到的信息，姓名：%s，性别：%d，手机号：%s", personTestResult.getName(), personTest.getSexValue(), personTest.getPhone(0).getNumber()));</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 方式二 ByteString：</span></span><br><span class="line">            <span class="comment">// 序列化</span></span><br><span class="line"><span class="comment">//            ByteString byteString = personTest.toByteString();</span></span><br><span class="line"><span class="comment">//            System.out.println(byteString.toString());</span></span><br><span class="line">            <span class="comment">// 反序列化</span></span><br><span class="line"><span class="comment">//            PersonTestProtos.PersonTest personTestResult = PersonTestProtos.PersonTest.parseFrom(byteString);</span></span><br><span class="line"><span class="comment">//            System.out.println(String.format("反序列化得到的信息，姓名：%s，性别：%d，手机号：%s", personTestResult.getName(), personTest.getSexValue(), personTest.getPhone(0).getNumber()));</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 方式三 InputStream</span></span><br><span class="line">            <span class="comment">// 粘包,将一个或者多个protobuf 对象字节写入 stream</span></span><br><span class="line">            <span class="comment">// 序列化</span></span><br><span class="line">            ByteArrayOutputStream byteArrayOutputStream = <span class="keyword">new</span> ByteArrayOutputStream();</span><br><span class="line">            personTest.writeDelimitedTo(byteArrayOutputStream);</span><br><span class="line">            <span class="comment">// 反序列化，从 steam 中读取一个或者多个 protobuf 字节对象</span></span><br><span class="line">            ByteArrayInputStream byteArrayInputStream = <span class="keyword">new</span> ByteArrayInputStream(byteArrayOutputStream.toByteArray());</span><br><span class="line">            PersonTestProtos.PersonTest personTestResult = PersonTestProtos.PersonTest.parseDelimitedFrom(byteArrayInputStream);</span><br><span class="line">            System.out.println(String.format(<span class="string">"反序列化得到的信息，姓名：%s，性别：%d，手机号：%s"</span>, personTestResult.getName(), personTest.getSexValue(), personTest.getPhone(<span class="number">0</span>).getNumber()));</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (InvalidProtocolBufferException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="五、message-部分语法说明"><a href="#五、message-部分语法说明" class="headerlink" title="五、message 部分语法说明"></a>五、message 部分语法说明</h2><ol>
<li><p>在 proto3 中，枚举的第一个常量名的编号必须为 0<br>在 proto3 中，由于默认值的规则进行了调整，而枚举的默认值为第一个，所以必须将第一个常量的编号置为 0，但是这与我们的业务有时候是有冲突的，所以，我们常将第一个常量设为：xx_UNSPECIFIED = 0，如：<code>ENUM_TYPE_UNSPECIFIED = 0；</code>，当然这不是我们自己约定的，这是 Google API Guilder 中建议的。</p>
</li>
<li><p>同一个 proto 文件中，多个枚举之间不允许定义相同的常量名<br>如下面的 message 在编译的时候就会报错 <code>IDEA is already defined in &quot;xxx&quot;</code>：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">enum IDE1 &#123;</span><br><span class="line">    IDEA = 0;</span><br><span class="line">    ECLIPSE = 1;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">enum IDE2 &#123;</span><br><span class="line">    IDEA = 7;</span><br><span class="line">    ECLIPSE = 8;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>关于数据类型匹配<br>见下图，摘自官网：<br><img src="http://blogsource.chenkaikai.com/uploads/2019/05/Protobuf02.png" alt="Protobuf 数据类型参考图"></p>
</li>
<li><p>关于默认值<br>proto3 中，数据的默认值不再支持自定义，而是由程序自行推倒：</p>
</li>
</ol>
<ul>
<li>string：默认值为空</li>
<li>bytes：默认值为空</li>
<li>bools：默认值为 false</li>
<li>数字类型：默认值为 0</li>
<li>枚举类型： 默认为定义的第一个元素，并且编号必须为 0</li>
<li>message 类型：默认值为 DEFAULT_INSTANCE，其值相当于空的 message</li>
</ul>
<h2 id="六、总结"><a href="#六、总结" class="headerlink" title="六、总结"></a>六、总结</h2><ol>
<li>XML、JSON、Protobuf 都具有数据结构化和数据序列化的能力</li>
<li>XML、JSON 更注重 <strong>数据结构化</strong>，关注人类可读性和语义表达能力。Protobuf 更注重 <strong>数据序列化</strong>，关注效率、空间、速度，人类可读性差，语义表达能力不足</li>
<li>Protobuf 的应用场景更为明确，XML、JSON 的应用场景更为丰富</li>
</ol>
<h2 id="七、其它"><a href="#七、其它" class="headerlink" title="七、其它"></a>七、其它</h2><ol>
<li>文档：<a href="https://developers.google.com/protocol-buffers/docs/proto3" target="_blank" rel="noopener">官网</a></li>
<li>上文使用的案例源码：<a href="https://github.com/goldenJet/JavaUtils/tree/master/com/jet/utils/protobuf" target="_blank" rel="noopener">[源码]</a></li>
<li>当然了，除了 Google 的 Protobuf，还有 Facebook 的 thrift，也值得研究一下哦，暂不进行赘述</li>
</ol>
<p><img src="http://blogsource.chenkaikai.com/cli_500px.png" alt></p>

      
    </div>

    

    
    
    
	
	<div>
	  
		<div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------ 本文结束 <i class="fa fa-fighter-jet"></i> 感谢阅读 ------</div>
    
</div>
	  
	</div>

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Google/" rel="tag"><i class="fa fa-tag"></i> Google</a>
          
            <a href="/tags/IM/" rel="tag"><i class="fa fa-tag"></i> IM</a>
          
            <a href="/tags/JAVA/" rel="tag"><i class="fa fa-tag"></i> JAVA</a>
          
            <a href="/tags/JSON/" rel="tag"><i class="fa fa-tag"></i> JSON</a>
          
            <a href="/tags/Protobuf/" rel="tag"><i class="fa fa-tag"></i> Protobuf</a>
          
            <a href="/tags/XML/" rel="tag"><i class="fa fa-tag"></i> XML</a>
          
            <a href="/tags/数据传输/" rel="tag"><i class="fa fa-tag"></i> 数据传输</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/crack-aspose/" rel="next" title="Word 转 pdf 之 Aspose 工具的“科学使用”">
                <i class="fa fa-chevron-left"></i> Word 转 pdf 之 Aspose 工具的“科学使用”
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Jet Chen</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">68</span>
                    <span class="site-state-item-name">posts</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">33</span>
                    <span class="site-state-item-name">categories</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">182</span>
                    <span class="site-state-item-name">tags</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/goldenJet" title="GitHub &rarr; https://github.com/goldenJet" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://twitter.com/goldenJ51015801" title="Twitter &rarr; https://twitter.com/goldenJ51015801" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、简介"><span class="nav-number">1.</span> <span class="nav-text">一、简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、关于-proto3"><span class="nav-number">2.</span> <span class="nav-text">二、关于 proto3</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、对比-JSON-和-XML"><span class="nav-number">3.</span> <span class="nav-text">三、对比 JSON 和 XML</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四、应用"><span class="nav-number">4.</span> <span class="nav-text">四、应用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#五、message-部分语法说明"><span class="nav-number">5.</span> <span class="nav-text">五、message 部分语法说明</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#六、总结"><span class="nav-number">6.</span> <span class="nav-text">六、总结</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#七、其它"><span class="nav-number">7.</span> <span class="nav-text">七、其它</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Jet Chen</span>

  

  
</div>









<div class="BbeiAn-info">
    <a target="_blank" href="http://www.miitbeian.gov.cn/" rel="nofollow">浙ICP备17005575号-1</a> <!--a标签中增加nofollow属性，避免爬虫出站。-->| 
	<a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=33010802009043" style="text-decoration:none;padding-left:17px;background:url(/images/icon-police.png) no-repeat left center" rel="nofollow">浙公网安备 33010802009043号</a>	  <!--这里将图标作为了背景，以使得能和后面的文字在同一行-->
</div>

        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/src/utils.js?v=7.0.0"></script>

  <script src="/js/src/motion.js?v=7.0.0"></script>



  
  


  <script src="/js/src/affix.js?v=7.0.0"></script>

  <script src="/js/src/schemes/pisces.js?v=7.0.0"></script>




  
  <script src="/js/src/scrollspy.js?v=7.0.0"></script>
<script src="/js/src/post-details.js?v=7.0.0"></script>



  


  <script src="/js/src/bootstrap.js?v=7.0.0"></script>



  


  


  




  

  

  

  

  

  

  

  

  

  

  

  

  

</body>
</html>
